﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Ruleweaver.Rules;

namespace Ruleweaver.Conditions
{
	public sealed class ConditionSchema : IConditionSchema
	{
		private readonly ISpecificationProvider _specificationProvider = new ConditionSchemaSpecificationProvider();
		private readonly IConditionRepository _conditionRepository;

		public ConditionSchema(IConditionRepository conditionRepository)
		{
			Contract.Requires(conditionRepository != null);

			_conditionRepository = conditionRepository;
		}

		#region IConditionSchema

		public Specification<T> GetSpecification<T>(T target, string conditionName)
		{
			return GetSpecification(target, new ConditionKey(typeof(T), conditionName));
		}
		#endregion

		private Specification<T> GetSpecification<T>(T target, ConditionKey conditionKey)
		{
			return new Specification<T>(target, GetRule(conditionKey), _specificationProvider);
		}

		private Rule GetRule(ConditionKey conditionKey)
		{
			var condition = _conditionRepository.GetCondition(conditionKey);

			return condition == null ? Rule.Fixed(true) : condition.Rule;
		}
	}
}